/*
	面积图
*/
define(
	[
		'require',
		'echarts',
		'echarts/chart/line',
		'zrender/tool/util',
		'apm/ui/business_chart_base',
		'apm/ui/echarts_component_categoryAxis_extend'
	],
	function (require) {
		"use strict";

		var echarts = require('echarts');
		var zrUtil = require('zrender/tool/util');
		var categoryAxisExtend = require('apm/ui/echarts_component_categoryAxis_extend');

		var forEach = Ember.EnumerableUtils.forEach;

		var axisLabelInterval = 10;

		var dataKeyRange;

		var LineView = require("apm/ui/business_chart_base").extend({
			didInsertElement: function(){
				this._super();
			},

			willDestroyElement: function(){
				categoryAxisExtend.unApplyTo(this.chart.id);
				this._super();
			},

			/**
			 * 初始化图表
			 */
			_initChart: function(){
				this._super();
				categoryAxisExtend.applyTo(this.chart.id);
			},

			/**
			 * 数据改变后, 刷新图表
			 */
			dataChange: Ember.observer("data", function(){
				if(!this.chart || !this.get("data")){
					return;
				}

				this._super();

				var bsView = Broada.getView("businessSequenceView");
				if(bsView) {
					bsView.overviewChart.connect(this.chart);
				}
			}),

			_getDefaultOption: function(){
				dataKeyRange = this.get("dataKeyRange");
				this.updateAxisLabelInterval();
				var view = this;
				return {
					title : {
						text: '',
						x: 'center',
						y: 1,
						padding:20,
						itemGap:0,
						textStyle:{
							color:"#fff"
						}
					},
					color: ['#f8ce69','#04da94','#00ddff'],
					grid: {
						x: 60,
						y: 20,
						x2: 50,
						y2: 30,
						borderWidth: 1,
						borderColor:"#215b92"
					},
					tooltip : {
						trigger: 'axis',
						position: function(pos){
							return [pos[0], 30];
						}
					},
					legend: {
						textStyle:{
							color:"#fff"
						},
						data:[]
					},
					xAxis : [
						{
							type : 'category',
							boundaryGap : false,
							axisLine: {
								show : false,
								lineStyle: {
									color:"#1f5992"
								}
							},

							axisTick : {
								show : true,
								lineStyle:{
									color:"#215b92"
								},
								interval: function(i, data){
									if(data.length < 5){
										return true;
									}
									if(dataKeyRange){
										if(parseInt(data.substring(3,5), 10) === 0 && parseInt(data.substring(0,2), 10) % 2 == 1 ){
											return true;
										}
									}else{
										if( parseInt(data.substring(3,5), 10)%5 === 0 ){
											return true;
										}
									}
								}
							},
							axisLabel : {
								show : true,
								textStyle:{
									color:"#5592c9"
								},
								interval: function(i, data){
									if(data.length < 5){
										return parseInt(data.split("时"||"日")[0])%2 == 0;
									}
									if(dataKeyRange){
										if(parseInt(data.substring(3,5), 10) === 0 && parseInt(data.substring(0,2), 10) % 2 == 1 ){
											return true;
										}
									}else{
										if( parseInt(data.substring(3,5), 10)%axisLabelInterval === 0 ){
											return true;
										}
									}
								},
								formatter: function(value){
									return view.get("FormatterInteger")?value.substring(0,value.indexOf(":")):value;
								}
							},
							splitLine: {
								show: true,
								lineStyle: {
									color:"#1f5992"
								},
								interval: function(i, data){
									if(data.length < 5){
										return true;
									}
									if(dataKeyRange){
										if(parseInt(data.substring(3,5), 10) === 0 && parseInt(data.substring(0,2), 10) % 2 == 1 ){
											return true;
										}
									}else{
										if( parseInt(data.substring(3,5), 10)%axisLabelInterval === 0 ){
											return true;
										}
									}
								}
							},
							data : []
						}
					],
					yAxis : [
						{	
							name : '',
							type : 'value',
							nameTextStyle : {
								color: '#aaa',
								align:'left'
							},
							min : 0,
							splitLine : {//分割线
								show : true,
								lineStyle: {
									color:"#1f5992"
								}
							},
							axisLine: {
								show : true,
								lineStyle:{
									color:"#1f5992"
								}
							},
							axisLabel : {
								show : true,
								textStyle:{
									color:"#5592c9"
								}
							}
						}
					],
					series : []
				};
			},

			_translateOption: function(option){
				this._translateXAxis(option);
				this._translateSeries(option);
				this._translateOther(option);
				if(this.get("indicator")){
					this.set("fmtType", this.get("indicator")["transform"]);
				}
				this._setFormatter(option);
			},

			_translateXAxis: function(option){
				var view = this;
				var data = this.get("data")||[];
				var xAxisData = option.xAxis[0].data = [];
				forEach(data, function(performance){
					xAxisData.push(view._translateXAxisDataItem(performance));
				});
			},

			_translateSeries: function(option){
				option.series.push({
					name: this.get("sName")||"",
					type:'line',
					itemStyle: {normal: {
						borderColor: "#fff",
						borderWidth:1,
						color: '#0672a3',
						areaStyle: {type: 'default',color:"rgba(0,221,255,0.8)"},lineStyle:{width:2,color:"#fff"}}
					},
					symbol: 'circle',
					symbolSize: 3,
					showAllSymbol: true,
					smooth:true,
					data:[]

				});
					
				var view = this;
				var data = this.get("data")||[];
				var seriesData = option.series[0].data;

				forEach(data, function(performance,index){

					switch(index){
						case 1:

						break;
						case 2:
						break;
						case 3:
						break;
					}
					if(overviewOrCenterSwitch == "business"){
						if(view.get("businessDataKey")){
							seriesData.push(view._translateSeriesDataItem(performance[view.get("businessDataKey")]));
						}else{
							seriesData.push(view._translateSeriesDataItem(performance[view.get("dataKey")]));
						}
						
					}else{
						seriesData.push(view._translateSeriesDataItem(performance[view.get("dataKey")]));
					}
					
				});
			},

			_translateOther: function(option){
				var title = this.get("title");
				option.title.text = title||"";
				
				option.yAxis[0].name = this.get("yName")||"";
				if(this.get("yMax")) {
					option.yAxis[0].max = this.get("yMax");
				}

				if(!this.hasData){
					option.yAxis[0].max = 100;
				}

				if(title){
					option.grid.y = 30;
				}

				if(this.dataKey && this.dataKey == "system/score/apdex"){
					option.yAxis[0].max = 1;
				}
				if(this.dataKey && this.dataKey == "business/score/apdex"){
					option.yAxis[0].max = 1;
				}
				// var threshold = this.get("threshold");
				// if(threshold) {
				// 	this._translateBaseLine(option, threshold);
				// }
			},

			_setFormatter: function(option){
				var fmtType = this.get("fmtType");
				if(typeof fmtType == "undefined" && this.dataKey == "system/response_time/avg"){
					fmtType = "transform_time";						
				}
				if(typeof fmtType == "undefined" && this.dataKey == "business/response_time/avg"){
					fmtType = "transform_time";						
				}
				function formate(tmp,value){
					forEach(value,function(param){
						forEach(param.data,function(v){
							if(v.value != "-"){
								tmp.push(v.value);
							}
						})
					});
					return Math.max.apply(null,tmp);
				}
				if(fmtType == "transform_time"){
					var tmp = [];//最大值
					var T = "ms";
					var Max = formate(tmp,option.series);
					if(1e3 > (Max / 1e3)){
						
					}else if(6e4 > (Max / 1e3)){
						T = "s";
					}else if (36e5 > (Max / 1e3)){
						T = "m";
					}else{
						T = "h";
					}
					option.yAxis[0].axisLabel.formatter = APM.util.indicatorFormatter_y(fmtType,T);
				}else if(fmtType == "transform_flow_mb"){
					var tmp = [];
					var T = "KB";
					var Max = formate(tmp,option.series);
					if(1e3 > (Max / 1e3)){
						
					}else if(1e6 > (Max / 1e3)){
						T = "MB";
					}else if (1e9 > (Max / 1e3)){
						T = "GB";
					}else{
						T = "TB";
					}
					option.yAxis[0].axisLabel.formatter = APM.util.indicatorFormatter_y(fmtType,T);
				}else if(fmtType == "transform_flow_kb"){
					var tmp = [];
					var T = "KB";
					var Max = formate(tmp,option.series);
					if(1e3 > (Max / 1e3)){
						
					}else if(1e6 > (Max / 1e3)){
						T = "MB";
					}else if (1e9 > (Max / 1e3)){
						T = "GB";
					}else{
						T = "TB";
					}
				}else if(fmtType == "transform_flow_bps"){
					var tmp = [];
					var T = "bps";
					var Max = formate(tmp,option.series);
					if(1e3 > Max ){
						
					}else if(1e3 > (Max / 1e3)){
						T = "Kbps";
					}else if (1e6 > (Max / 1e3)){
						T = "Mbps";
					}else{
						T = "Gbps";
					}
				}else{
					option.yAxis[0].axisLabel.formatter = APM.util.indicatorFormatter(fmtType);
				}
				option.tooltip.formatter = this._tooltipFormatter(fmtType);
			},

			_translateXAxisDataItem: function(performance){
				if(this.get("size") == 'hour')

					return (new Date(performance.timestamp)).getHours()+'时';
				if(this.get("size") == 'day')
				
					return (new Date(performance.timestamp)).getDate()+'日';
				return (new Date(performance.timestamp)).toTimeString().substr(0, 5);	
			},

			_translateSeriesDataItem: function(orgiVal){

				var value = Ember.isNone(orgiVal) ? "-" : orgiVal;

				if(value !== "-"){
					this.hasData = true;
				}

				return {
					value: value,
					orgiVal: orgiVal
				};
			},

			// _translateBaseLine: function(option, threshold) {
			// 	var dataKey = this.get("dataKey");
			// 	if("system/throughput/total" == dataKey) {
			// 		this._thresholdLevel(option, threshold, "rpm");
			// 	} else if("system/response_time/avg" == dataKey) {
			// 		this._thresholdLevel(option, threshold, "rtt");
			// 	} else if("system/error/count" == dataKey) {
			// 		this._thresholdLevel(option, threshold, "error");
			// 	}
			// },

			// _thresholdLevel: function(option, threshold, key) {
			// 	var view = this,
			// 		array = [];

			// 	if(!threshold.thresholdParam){ return; }

			// 	forEach(threshold.thresholdParam, function(param){
			// 		if(key == param.indicator) {
			// 			var level = param.level;
			// 			if(level) {
			// 				var highValue = 0;
			// 				if(level['10']) {
			// 					highValue = level['10'];
			// 					array.push({"key":10,"value":highValue});
			// 				}
			// 				if(level['20']) {
			// 					highValue = level['20'];
			// 					array.push({"key":20,"value":highValue});
			// 				}
			// 				if(level['50']) {
			// 					highValue= level['50'];
			// 					array.push({"key":50,"value":highValue});
			// 				}
			// 				view._maxValue(option, highValue);
			// 			}
			// 			var markLine = option.series[0].markLine;
			// 			view._translateMarkLine(markLine,array);
			// 		}
			// 	});
			// },

			// _maxValue:function(option, value) {
			// 	var data = this.get("data"),
			// 		dataKey = this.get("dataKey"),
			// 		max=0;

			// 	forEach(data, function(performance){
			// 		var p = performance[dataKey];
			// 		if(max<p){
			// 			max=p;
			// 		}
			// 	});
			// 	if(max<value) {
			// 		option.yAxis[0].max = value<5?5:Math.round(value*1.2/10)*10;
			// 	}
			// },

			// _translateMarkLine: function(markLine, array) {
			// 	var thr = [];

			// 	for(var i=0; i < array.length; i++) {
			// 		var thrData = [];
			// 		var start = {
			// 			severity:array[i]['key'],
			// 			value:array[i]['value'],
			// 			xAxis:0,
			// 			yAxis:array[i]['value']
			// 		};
			// 		var end1 = {
			// 			xAxis:60,
			// 			yAxis:array[i]['value']
			// 		};
			// 		thrData.push(start);
			// 		thrData.push(end1);

			// 		thr.push(thrData);
			// 	}

			// 	markLine.data = thr;
			// },

			_tooltipFormatter: function(type){
				return function(params, ticket, callback){
					params = Ember.A(params||[]);
					var formatter = APM.util.indicatorFormatter(type);
					var tooltip = params[0].name;
					params.forEach(function(param){
						tooltip +=  '<br/>' + param.seriesName + '：' + formatter(param.data.orgiVal);
					});
					return tooltip;
				}
			},

			_resizeChart: function(){
				this.updateAxisLabelInterval();
				this._super();
			},

			updateAxisLabelInterval: function(){
				// var width = this.$().width();
				var width = window.screen.width;
		
				if(width >1440){
					axisLabelInterval = 5;
				}else if (width <1280){
					axisLabelInterval = 15;
				}else if(width >= 1280&&width <=1440){
					axisLabelInterval = 10;
				}
				// if((width/12) > 45){
				// 	axisLabelInterval = 5;
				// }else if (width < 300){
				// 	axisLabelInterval = 15;
				// }else{
				// 	axisLabelInterval = 10;
				// }
			}
		});
		return LineView;
	}
);